/**
 * 方法说明
 * author: Keil
 * description: 内部业务基础接口方法
 * @param
 * @return
 * @createTime: 2022-07-04 17:25:23
 */
const appImageBaseUrl = "https://admin.ximusen.cn/profile/upload/ximusen_mini_app_img/";
const TIMEOUT = 10000;
// const baseUrl = "http://smosun.t3.wmeimob.cn";
// const baseUrl = 'http://192.168.1.25:8180'
const baseUrl='https://wx.ximusen.cn';
import store from "@/store/index.js";

//不带token请求 表单方式
const httpRequest = (url, data, method, hideLoading) => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        });
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            data: data,
            timeout: TIMEOUT,
            header: {
                "content-type": "application/x-www-form-urlencoded",
            },
            method: method,
            success: (res) => {
                !hideLoading && uni.hideLoading();
                if (res.statusCode == 200) {
                    if (res.data.code == 0) {
                        resolve(res.data);
                    } else {
                        if (res.data.message != null && res.data.message != "") {
                            uni.showToast({
                                title: res.data.message,
                                icon: "none",
                            });
                            resolve(res);
                        }
                    }
                }
            },
            fail: (res) => {
                console.log("fail" + JSON.stringify(res) + baseUrl + url);
                !hideLoading && uni.hideLoading();
                if (!hideLoading) {
                    uni.showToast({
                        title: "网络不给力，请稍后再试~",
                        icon: "none",
                    });
                }
                reject(res);
            },
        });
    });
};

//不带token请求 json方式
const httpJsonRequest = (url, data, method, hideLoading) => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        });
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            data: data,
            timeout: TIMEOUT,
            header: {
                "content-type": "application/json",
            },
            method: method,
            success: (res) => {
                !hideLoading && uni.hideLoading();
                if (res.statusCode == 200) {
                    if (res.data.code == 0) {
                        resolve(res.data);
                    } else {
                        if (res.data.message != null && res.data.message != "") {
                            uni.showToast({
                                title: res.data.message,
                                icon: "none",
                            });
                            resolve(res);
                        }
                    }
                }
            },
            fail: (res) => {
                console.log("fail" + JSON.stringify(res) + baseUrl + url);
                !hideLoading && uni.hideLoading();
                if (!hideLoading) {
                    uni.showToast({
                        title: "网络不给力，请稍后再试~",
                        icon: "none",
                    });
                }
                reject(res);
            },
        });
    });
};
// 刷新token
const refreshToken = () => {
    uni.login({
        provider: "weixin",
        success: (res) => {
            var data = {};
            data.code = res.code;
            httpJsonRequest("/mp-api/wx/auth/code", data, "POST", true).then((res) => {
                if (res.code == 0) {
                    if (res.data != null) {
                        if (res.data.uid != 0) {
                            setToken(res.data.accessToken);
                            store.commit("loginSaveUserInfo", res.data);
                        }
                    }
                }
            });
        },
    });
};
// token缓存
const setToken = (token) => {
    uni.setStorageSync("Token", token);
};
// 取token
const getToken = () => {
    return uni.getStorageSync("Token");
};
//带token请求 表单方式
const httpTokenRequest = (url, data, method, hideLoading) => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        });
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            data: data,
            header: {
                "content-type": "application/x-www-form-urlencoded",
                "x-accesstoken": getToken(),
            },
            timeout: TIMEOUT,
            method: method,
            success: (res) => {
                !hideLoading && uni.hideLoading();

                //踢出登录 或者 token过期
                if (res.statusCode == 401 || res.statusCode == 402 || res.statusCode == 403) {
                    store.commit("logout");
                    uni.removeStorage({
                        key: "Token",
                    });
                    // refreshToken();
                    return uni.navigateTo({ url: "/pages/login/login" });
                } else {
                    if (res.data.code == 0) {
                        resolve(res.data);
                    } else {
                        if (res.data.code == 404 || res.data.code == 999) {
                            store.commit("logout");
                            uni.removeStorage({
                                key: "Token",
                            });
                            refreshToken();
                            resolve(res.data);
                            return uni.navigateTo({ url: "/pages/login/login" });
                        } else {
                            if (res.data.message != null && res.data.message != "") {
                                uni.showToast({
                                    title: res.data.message,
                                    icon: "none",
                                });
                            }
                            resolve(res.data);
                        }
                    }
                }
            },
            fail: (res) => {
                console.log("fail" + JSON.stringify(res) + baseUrl + url);
                !hideLoading && uni.hideLoading();
                if (!hideLoading) {
                    uni.showToast({
                        title: "网络不给力，请稍后再试~",
                        icon: "none",
                    });
                }
                reject(res);
            },
        });
    });
};

//带token请求 json方式
const httpTokenJsonRequest = (url, data, method, hideLoading) => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        });
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            data: data,
            header: {
                "content-type": "application/json",
                "x-accesstoken": getToken(),
            },
            timeout: TIMEOUT,
            method: method,
            success: (res) => {
                !hideLoading && uni.hideLoading();

                //踢出登录 或者 token过期
                if (res.statusCode == 401 || res.statusCode == 402 || res.statusCode == 403) {
                    store.commit("logout");
                    uni.removeStorage({
                        key: "Token",
                    });
                    // refreshToken();

                    return uni.navigateTo({ url: "/pages/login/login" });
                } else {
                    if (res.data.code == 0) {
                        resolve(res.data);
                    } else {
                        if (res.data.code == 404 || res.data.code == 999) {
                            store.commit("logout");
                            uni.removeStorage({
                                key: "Token",
                            });
                            refreshToken();
                            resolve(res.data);
                            return uni.navigateTo({ url: "/pages/login/login" });
                        } else {
                            if (res.data.message != null && res.data.message != "") {
                                if (url != "/mp-api/wx/device/add") {
                                    uni.showToast({
                                        title: res.data.message,
                                        icon: "none",
                                    });
                                }
                                resolve(res.data);
                            } else {
                                reject(res.data);
                            }
                        }
                    }
                }
            },
            fail: (res) => {
                console.log("fail" + JSON.stringify(res) + baseUrl + url);
                !hideLoading && uni.hideLoading();
                if (!hideLoading) {
                    uni.showToast({
                        title: "网络不给力，请稍后再试~",
                        icon: "none",
                    });
                }
                reject(res);
            },
        });
    });
};
const formatDate = (formatStr, fdate) => {
    //日期格式化
    if (fdate) {
        if (~fdate.indexOf(".")) {
            fdate = fdate.substring(0, fdate.indexOf("."));
        }
        fdate = fdate.toString().replace("T", " ").replace(/\-/g, "/");
        var fTime,
            fStr = "ymdhis";
        if (!formatStr) formatStr = "y-m-d h:i:s";
        if (fdate) fTime = new Date(fdate);
        else fTime = new Date();
        var month = fTime.getMonth() + 1;
        var day = fTime.getDate();
        var hours = fTime.getHours();
        var minu = fTime.getMinutes();
        var second = fTime.getSeconds();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        hours = hours < 10 ? "0" + hours : hours;
        minu = minu < 10 ? "0" + minu : minu;
        second = second < 10 ? "0" + second : second;
        var formatArr = [
            fTime.getFullYear().toString(),
            month.toString(),
            day.toString(),
            hours.toString(),
            minu.toString(),
            second.toString(),
        ];
        for (var i = 0; i < formatArr.length; i++) {
            formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
        }
        return formatStr;
    } else {
        return "";
    }
};

const getDateTimeFormat = (unixtime) => {
    var currTime = Date.parse(new Date());
    var winTime = new Date(unixtime.replace(/-/g, "/")).getTime();
    var time = parseInt(currTime) / 1000 - parseInt(winTime) / 1000;
    time = Math.abs(time);
    if (time < 60) {
        return "刚刚";
    }
    var minutes = time / 60;
    if (minutes < 60) {
        return Math.floor(minutes) + "分钟前";
    }
    var hours = time / 3600;
    if (hours < 24) {
        return Math.floor(hours) + "小时前";
    }
    return formatDate("y-m-d h:i", unixtime);
};
export default {
    appImageBaseUrl,
    baseUrl,
    httpRequest,
    httpJsonRequest,
    httpTokenRequest,
    httpTokenJsonRequest,
    setToken,
    getToken,
    formatDate,
    getDateTimeFormat,
};
